import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

import { reqUserAddressList } from '@/api/user'

Vue.use(Vuex)

// 初始化仓库
const store = new Vuex.Store({
  state: {
    token: '',
    refreshToken: '',
    userInfo: {},
    shopCarData: [], // 每一个商品的数据结构： [{id:88,number,selected,price},{id:99,number,selected,price}]
    selectAddressInfo: {}, // 记录当前用户购物车选中的地址
    isShowUseAddressButton: false, // 是否显示使用此地址按钮
  },
  mutations: {
    setSelectAddressInfo(state, selectAddressInfo) {
      console.log('selectAddressInfo', selectAddressInfo)
      state.selectAddressInfo = selectAddressInfo
    },
    clearShopCar(state) {
      state.shopCarData = []
      state.selectAddressInfo = {}
      state.isShowUseAddressButton = false
    },
    addGoodsToCart(state, goods) {
      let index = state.shopCarData.findIndex((item) => item.id === goods.id)
      // 判断是否有相同商品，有相同商品则累加数量
      if (index > -1) {
        state.shopCarData[index].number += goods.number
      } else {
        // 没有相同商品才push
        state.shopCarData.push(goods)
      }
    },
    setToken(state, { token, refreshToken }) {
      state.token = token
      state.refreshToken = refreshToken
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setUseAddressButton(state, bool) {
      state.isShowUseAddressButton = bool
    },
    clearToken(state) {
      state.token = ''
      state.refreshToken = ''
    },
    clearUserInfo(state) {
      state.userInfo = {}
    },
    setAvatar(state, avatar) {
      state.userInfo.avatar = avatar
    },
    delCarGoods(state, id) {
      let index = state.shopCarData.findIndex((item) => item.id == id)
      if (index > -1) {
        state.shopCarData.splice(index, 1)
      }
    },
    setCarGoodsSelected(state, id) {
      let index = state.shopCarData.findIndex((item) => item.id == id)
      if (index > -1) {
        state.shopCarData[index].selected = !state.shopCarData[index].selected
      }
    },
    setCarGoodsNumber(state, { id, number }) {
      let index = state.shopCarData.findIndex((item) => item.id == id)
      if (index > -1) {
        state.shopCarData[index].number = number
      }
    },
  },
  getters: {
    // 判断是否有地址
    hasAddress(state) {
      if (Object.keys(state.selectAddressInfo).length === 0) {
        // 没有地址
        return false
      } else {
        // 有地址
        return true
      }

      // Object.keys(state.selectAddressInfo).length !== 0
    },
    // 判断购物车是否有商品
    isCarEmpty(state) {
      return state.shopCarData.length === 0
    },
    // 返回对象格式：{商品id:选中状态,...}
    getGoodsSelected(state) {
      let obj = {}
      state.shopCarData.forEach(({ id, selected }) => {
        obj[id] = selected
      })
      return obj
    },
    // 返回对象格式：{商品id:数量,...}
    getGoodsNumber(state) {
      let obj = {}
      state.shopCarData.forEach(({ id, number }) => {
        obj[id] = number
      })
      return obj
    },

    // 获取购物车商品id组成的字符串
    getCarGoodsIds(state) {
      // '88,99'
      let ids = state.shopCarData.map((item) => item.id).join(',')

      // 最后一位是逗号
      if (ids.charAt(ids.length - 1) === ',') {
        return ids.substring(0, ids.length - 1)
      }

      // 第一位是逗号
      if (ids.charAt(0) === ',') {
        return ids.substring(1)
      }
      return ids
    },

    // 获取购物车选中的商品id组成的字符串
    getCarSelectedGoodsIds(state) {
      // '88,99'
      let ids = state.shopCarData
        .map((item) => {
          if (item.selected) {
            return item.id
          }
        })
        .join(',')

      // 最后一位是逗号
      if (ids.charAt(ids.length - 1) === ',') {
        return ids.substring(0, ids.length - 1)
      }

      // 第一位是逗号
      if (ids.charAt(0) === ',') {
        return ids.substring(1)
      }
      return ids
    },

    // 获取购物车商品总数量
    getCarNumber(state) {
      return state.shopCarData.reduce((result, item) => {
        result += parseInt(item.number)
        return result
      }, 0)
    },

    // 获取购物车商品选中总数量
    getCarSelectedNumber(state) {
      return state.shopCarData.reduce((result, item) => {
        if (item.selected) {
          result += parseInt(item.number)
        }
        return result
      }, 0)
    },

    // 获取购物车商品选中的总价格
    getCarSelectedPrice(state) {
      let totalPrice = state.shopCarData.reduce((result, item) => {
        if (item.selected) {
          result += item.number * item.price
        }
        return result
      }, 0)

      totalPrice = totalPrice * 100

      return totalPrice
    },
  },
  actions: {
    // 获取用户地址
    async getUserAddress({ commit }) {
      let userAllAddress = await reqUserAddressList()

      // 分情况： 1.没有地址, 2. 仅有一个地址  3. 超过1个地址(看是否有默认)
      if (userAllAddress.length === 0) {
        commit('setSelectAddressInfo', {})
      }

      if (userAllAddress.length === 1) {
        commit('setSelectAddressInfo', userAllAddress[0])
      } else if (userAllAddress.length > 1) {
        const result = userAllAddress.filter((item) => item.isDefault)
        if (result.length > 0) {
          // 说明找到了默认地址，赋值给selectAddressInfo
          commit('setSelectAddressInfo', result[0])
        } else {
          // 没有默认地址，则将第一个地址赋值给selectAddressInfo
          commit('setSelectAddressInfo', userAllAddress[0])
        }
      }
      return userAllAddress.length
      // return undefined  // 等价于 Promise.resolve(undefined)
    },
  },
  plugins: [
    createPersistedState({
      reducer(state) {
        // 仅持久化下面的状态
        return {
          token: state.token,
          refreshToken: state.refreshToken,
          userInfo: state.userInfo,
          shopCarData: state.shopCarData,
          isShowUseAddressButton: state.isShowUseAddressButton,
        }
      },
    }),
  ],
})

// 导出仓库
export default store
